package com.back.config;

import com.back.security.JwtAuthenticationEntryPoint;
import com.back.security.JwtAuthenticationFilter;
import com.back.security.RoleBasedAccessDeniedHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * Spring Security配置类
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;
    
    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;
    
    @Autowired
    private RoleBasedAccessDeniedHandler accessDeniedHandler;
    
    @Autowired
    private JwtAuthenticationEntryPoint unauthorizedHandler;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // 关闭CSRF保护
            .csrf().disable()
            // 设置认证失败处理类
            .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
            // 基于token，所以不需要session
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
            // 过滤请求
            .authorizeRequests()
            // 对于登录注册相关的接口 允许匿名访问
            .antMatchers("/api/auth/**").permitAll()
            // swagger相关接口
            .antMatchers("/swagger-ui.html").permitAll()
            .antMatchers("/swagger-resources/**").permitAll()
            .antMatchers("/webjars/**").permitAll()
            .antMatchers("/v2/**").permitAll()
            // 静态资源
            .antMatchers("/static/**").permitAll()
            // 测试接口
            .antMatchers("/test/**").permitAll()
            // 跨域请求会先进行一次options请求
            .antMatchers("/**/favicon.ico").permitAll()
            .antMatchers("/*/api-docs").permitAll()
            // 公共接口放行
            .antMatchers("/common/job/search", "/common/job/*/", "/common/company/*", "/common/job/categories").permitAll()
            
            // 管理员权限
            .antMatchers("/admin/**").hasRole("ADMIN")
            // 求职者权限
            .antMatchers("/jobseeker/**").hasRole("JOB_SEEKER")
            // 企业招聘人员权限
            .antMatchers("/employer/**").hasRole("EMPLOYER")
            
            // 管理员和企业招聘人员共享的权限
            .antMatchers("/job/verify/**").hasAnyRole("ADMIN", "EMPLOYER")
            // 管理员和求职者共享的权限
            .antMatchers("/resume/**").hasAnyRole("ADMIN", "JOB_SEEKER")
            
            // 其他所有请求需要认证
            .anyRequest().authenticated();
                
        // 添加JWT过滤器
        http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
        
        // 禁用缓存
        http.headers().cacheControl();
    }
} 